package com.adk.backend.util;

import com.adk.backend.entity.LxActionLogs;
import com.adk.backend.mapper.ActionLogsMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * 日志工具类
 */
@Slf4j
@Component
public class LogUtil {
    
    @Autowired
    private ActionLogsMapper actionLogsMapper;
    
    /**
     * 记录操作日志
     * @param userId 用户ID
     * @param tableName 表名
     * @param recordId 记录ID
     * @param remarks 操作备注
     * @param oldData 旧数据（可选）
     * @param newData 新数据（可选）
     */
    public void logAction(Long userId, String tableName, Long recordId, String remarks, String oldData, String newData) {
        try {
            LxActionLogs actionLog = new LxActionLogs();
            actionLog.setUId(userId);
            actionLog.setTbName(tableName);
            actionLog.setTbId(recordId);
            actionLog.setRemarks(remarks);
            if (oldData != null) {
                actionLog.setOldData(oldData);
            }
            if (newData != null) {
                actionLog.setNewData(newData);
            }
            actionLog.setAddTime((int) (System.currentTimeMillis() / 1000));
            
            actionLogsMapper.insert(actionLog);
        } catch (Exception e) {
            log.error("记录操作日志失败", e);
        }
    }
    
    /**
     * 记录操作日志（简化版，兼容旧代码）
     */
    public void logAction(Long userId, String tableName, Long recordId, String remarks) {
        logAction(userId, tableName, recordId, remarks, null, null);
    }
    
    /**
     * 获取客户端IP地址
     */
    private String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}

